<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            position: absolute;
            width: 100px;
            height: 100px;
            background-color: pink;
        }
    </style>
</head>

<body>
    <button>胡歌500</button>
    <button>胡歌800</button>
    <div>胡歌</div>
    <script>
        let div1 = document.querySelector('div')
        function a(o, m ,f) {
            // 有个按钮就会一直触发所以触发前先清除之前的定时器就不会加速
            clearInterval(o.b)
            o.b = setInterval(c, 15)
            function c() {
                step = (m - o.offsetLeft) / 10;
                // console.log(step);
                step = step > 0 ? Math.ceil(step) : Math.floor(step)
                if (o.offsetLeft == m) {
                    clearInterval(o.b)
                    
                    // 回调函数要到定时器结束调用
                    f()
                }
                // 匀速：目标值+固定值
                // o.style.left = o.offsetLeft + 1 + 'px'

                // 缓速：步长公式（目标值-当前值）/ 10
                o.style.left = o.offsetLeft + step + 'px'
            }
        }

        let btn = document.querySelectorAll('button')
        btn[0].addEventListener('click', function () {
            a(div1, 500)
        }) 
        btn[1].addEventListener('click', function () {
            a(div1, 800 , function(){
                div1.style.backgroundColor='green'
            })
        }) 
    </script>

</body>

</html>